package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.MenuService;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys_role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;


/*    @GetMapping("/list")
    public ResultData list(String name,int page,int limit){
        //创建分页构造器,查询系统用户信息
        Page<User> pageInfo = new Page<>(page,limit);
        Page<SysUserInfo> userInfoPage = new Page<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,User::getName,name);
        queryWrapper.orderByDesc(User::getCreate_date);
        //分页查询
        userService.page(pageInfo,queryWrapper);
        //Copy
        BeanUtils.copyProperties(pageInfo,userInfoPage,"records");
        //遍历集合,添加元素
        List<User> records = pageInfo.getRecords();
        List<SysUserInfo> collect = records.stream().map(item -> {
            SysUserInfo sysUserInfo = new SysUserInfo();
            BeanUtils.copyProperties(item, sysUserInfo);

            //获取角色ID,添加角色信息
            //查询用户角色id集合: role_id
            String[] rowIds = item.getRole_id().replace("[", "")
                    .replace("]", "")
                    .replace("\"", "")
                    .split(",");
            List<String> ids = new ArrayList<>();
            Collections.addAll(ids, rowIds);
            List<Role> roles = roleService.listByIds(ids);
            List<String> strings = roles.stream().map(getRoleName -> {
                String s = getRoleName.getName();
                return s;
            }).collect(Collectors.toList());
            sysUserInfo.setRole_id(ids);
            sysUserInfo.setRolename(strings);
            return sysUserInfo;
        }).collect(Collectors.toList());

        userInfoPage.setRecords(collect);
       // List<SysUserInfo> data = userInfoPage.getRecords();

        return ResultData.ok("", PageResult.init(userInfoPage.getTotal(),userInfoPage.getSize(),userInfoPage.getCurrent(),userInfoPage.getRecords()));
    }*/

    @GetMapping("/list")
    public ResultData list(String name, int page, int limit) {
        //创建分页构造器
        Page<Role> rolePage = new Page<>(page, limit);
        Page<RoleDto> roleDtoPage = new Page<>();
        //条件查询
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Role::getName, name);
        roleService.page(rolePage, queryWrapper);
        //Copy
        BeanUtils.copyProperties(rolePage, roleDtoPage, "records");

        List<Role> roles = rolePage.getRecords();
        List<RoleDto> roleDtos = roles.stream().map(item -> {
            RoleDto roleDto = new RoleDto();
            BeanUtils.copyProperties(item, roleDto);
            LambdaQueryWrapper<RoleMenu> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(RoleMenu::getRole_id, item.getId());
            List<RoleMenu> list = roleMenuService.list(queryWrapper1);
            List<String> collect = list.stream().map(ids -> {
                String menu_id = ids.getMenu_id();
                return menu_id;
            }).collect(Collectors.toList());
            roleDto.setRole_id(item.getId());
            roleDto.setMenu_id(collect);
            return roleDto;
        }).collect(Collectors.toList());
        roleDtoPage.setRecords(roleDtos);

        return ResultData.ok("", PageResult.init(roleDtoPage.getTotal(), roleDtoPage.getSize(), roleDtoPage.getCurrent(), roleDtoPage.getRecords()));


    }

    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        //获取管理员信息
        Role role = roleService.getById(id);
        //获取对应的菜单表
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRole_id, id);
        List<RoleMenu> list = roleMenuService.list(queryWrapper);
        //获取菜单对应编号的IDS
        List<String> ids = list.stream().map(item -> {
            String menu_id = item.getMenu_id();
            return menu_id;
        }).collect(Collectors.toList());
        //获取一级菜单
        LambdaQueryWrapper<Menu> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Menu::getPid, 0);
        queryWrapper1.in(Menu::getId, ids);
        List<Menu> list1 = menuService.list(queryWrapper1);
        //遍历一级菜单,获取一级菜单下面的二级菜单
        List<MenuDto> collect = list1.stream().map(oneMenu -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(oneMenu, menuDto);
            //找出二级菜单
            LambdaQueryWrapper<Menu> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Menu::getPid, oneMenu.getId());
            queryWrapper2.in(Menu::getId, ids);
            List<Menu> list2 = menuService.list(queryWrapper2);
            //遍历2级菜单,复制菜单到dto中,二级菜单中包含三级菜单
            List<MenuDto> list4 = list2.stream().map(twoMenu -> {
                MenuDto menuDtoTwo = new MenuDto();
                BeanUtils.copyProperties(twoMenu, menuDtoTwo);
                LambdaQueryWrapper<Menu> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(Menu::getPid, twoMenu.getId());
                queryWrapper3.in(Menu::getId, ids);
                List<Menu> list3 = menuService.list(queryWrapper3);
                menuDtoTwo.setChildren(list3);
                return menuDtoTwo;
            }).collect(Collectors.toList());

            menuDto.setChildren(Collections.unmodifiableList(list4));
            return menuDto;
        }).collect(Collectors.toList());

        RoleDto roleDto = new RoleDto();
        BeanUtils.copyProperties(role, roleDto);
        roleDto.setAuthList(collect);

        return ResultData.ok("", roleDto);

    }

    @PostMapping("/update")
    public ResultData update(@RequestBody RoleDto roleDto) {
        roleService.updateRoleAndMenu(roleDto);
        return ResultData.ok("修改成功", null);
    }

    @GetMapping("/allData")
    public ResultData allData() {
        List<Role> list = roleService.list();
        return ResultData.ok("", list);
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody RoleDto roleDto) {
        roleDto.setCreate_date(LocalDateTime.now());
        roleService.save(roleDto);
        //新增菜单
        List<String> ids = roleDto.getMenuids();
        if (ids == null) {
            return ResultData.ok("新增成功", null);
        }
        for (String id : ids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenu_id(id);
            roleMenu.setRole_id(roleDto.getId());
            roleMenuService.save(roleMenu);

        }
        return ResultData.ok("新增成功", null);
    }

    @GetMapping("/del")
    public ResultData del(String id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole_id, id);
        List<User> list = userService.list(queryWrapper);
        if (list.size() != 0){
            throw new BusinessException("该角色下面有用户,不能删除");
        }
        roleService.removeById(id);
        return ResultData.ok("删除成功",null);

    }
}
